package com.chengxiaoxiao.ai_demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengxiaoxiao.ai_demo.convertor.KnowledgeBaseConvertor;
import com.chengxiaoxiao.ai_demo.entity.KnowledgeBase;
import com.chengxiaoxiao.ai_demo.mapper.KnowledgeBaseMapper;
import com.chengxiaoxiao.ai_demo.service.KnowledgeBaseService;
import com.chengxiaoxiao.ai_demo.service.KnowledgeFileService;
import com.chengxiaoxiao.ai_demo.vo.form.KnowledgeBaseForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * knowledgeBase 服务实现类
 *
 * @Description:
 * @Author: Cheng Xiaoxiao
 * @Date: 2025-03-14 16:50:21
 */
@Service
@RequiredArgsConstructor
public class KnowledgeBaseServiceImpl extends ServiceImpl<KnowledgeBaseMapper, KnowledgeBase> implements KnowledgeBaseService {
    private final KnowledgeBaseConvertor knowledgeBaseConvertor;
    private final KnowledgeFileService knowledgeFileService;

    /**
     * 获取knowledgeBase详情
     *
     * @param id ID
     * @return 单个knowledgeBase详情
     */
    @Override
    public KnowledgeBase detailById(String id) {
        return getById(id);
    }

    /**
     * 增加knowledgeBase
     *
     * @param knowledgeBaseForm 知识库构建表单
     * @return 增加后的数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public KnowledgeBase saveKnowledgeBase(KnowledgeBaseForm knowledgeBaseForm) {
        //1. 先添加知识库信息
        KnowledgeBase knowledgeBase = knowledgeBaseConvertor.knowledgeBase2KnowledgeBaseForm(knowledgeBaseForm);
        this.baseMapper.insert(knowledgeBase);

        //2. 如果存在文件，将文件保存起来，并进行嵌入
        if (CollUtil.isNotEmpty(knowledgeBaseForm.getMultipartFiles())) {
            knowledgeFileService.batchAddFiles(knowledgeBase.getId(), knowledgeBaseForm.getMultipartFiles());
        }

        return knowledgeBase;
    }

    /**
     * 修改knowledgeBase
     *
     * @param knowledgeBase knowledgeBase对象
     * @return 修改后的数据
     */
    @Override
    public KnowledgeBase updateKnowledgeBaseById(KnowledgeBase knowledgeBase) {
        this.baseMapper.updateById(knowledgeBase);
        return knowledgeBase;
    }

    /**
     * 根据ID删除
     *
     * @param id ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        removeById(id);
        //删除知识库文件
        knowledgeFileService.deleteByKnowledgeBaseId(id);
    }
}